package dryven.model.validation.validators;

import java.util.Calendar;
import java.util.Date;

import dryven.model.validation.ValidationReporter;
import dryven.model.validation.ValidationFormValueCollection;
import dryven.model.validation.ValidationFieldDescription;
import dryven.model.validation.Validator;

public class DateValidator implements Validator {

	public static final String INVALID_DATE_KEY = "dryven-invalid-date";
	
	@Override
	public void validate(ValidationFieldDescription desc, ValidationFormValueCollection form,
			ValidationReporter reporter) {
		String name = desc.getName();
		String day = null;
		String month = null;
		String year = null;
		
		if(form.getValue(name)!=null) {
			String[] dateParts = form.getValue(name).split("/");
			if(dateParts.length!=3) {
				reporter.reportError(name, INVALID_DATE_KEY, form.getValue(name));
				return;
			}
			day = dateParts[0];
			month = dateParts[1];
			year = dateParts[2];
		} else {
			day = form.getValue(name+"_day");
			month = form.getValue(name+"_month");
			year = form.getValue(name+"_year");
		}
		
		if(day!=null && month!=null && year!=null) {
			int nDay = 0;
			int nMonth = 0;
			int nYear = 0;
			try {
				nDay = Integer.parseInt(day);
				nMonth = Integer.parseInt(month);
				nYear = Integer.parseInt(year);
			} catch(NumberFormatException e) {
				reporter.reportError(name, INVALID_DATE_KEY, day+"/"+month+"/"+year);
				return;
			}
			
			if(desc.getValueType().equals(Calendar.class)) {
				Calendar c = Calendar.getInstance();
				c.set(Calendar.DAY_OF_MONTH, nDay);
				c.set(Calendar.MONTH, nMonth);
				c.set(Calendar.YEAR, nYear);
				reporter.valueConverted(c);
			} else if(desc.getValueType().equals(Date.class)) {
				Date d = new Date(nYear, nMonth, nDay);
				reporter.valueConverted(d);
			}
			
		}
		else {
			reporter.reportError(name, Validator.FIELD_NOT_FOUND_ERROR, name);
		}
	}


}
